# 开始场景
import pandas as pd
import pygame
import os

from data.level_data import LevelData
from shared_variables import WHITE, CONFIG, BLACK, FONT
from scenes.base_scene import Scene


class StartSelectCharacterScene(Scene):
    def __init__(self, screen: pygame.surface.Surface, level_data: LevelData):
        super().__init__()
        self.screen = screen
        self.background = pygame.image.load(CONFIG['assets']['background']['select'])  # 加载背景图片
        self.level_data = level_data
        self.characters: pd.DataFrame = level_data.load_characters()
        self.character_index = 1
        self.current_path = os.path.curdir
        self.rects = {}

    def handle_events(self, event):
        if event.type == pygame.MOUSEBUTTONDOWN:
            mouse_pos = pygame.mouse.get_pos()
            for i, character in self.characters.iterrows():
                if self.rects[i].collidepoint(mouse_pos):
                    # self.level_data.set_me_character_id(i)
                    # self.level_data.initialize_random_role(i)
                    # self.level_data.temp_init_task_arrangement()
                    return "office_scene"
        return None

    def calculate_item_positions(self):
        num_items = len(self.characters)

        item_height = CONFIG['screen']['height'] // (num_items // 2 + 1)  # 计算每个项的高度
        item_positions = []

        for i in range(num_items):
            item_width = ((i % 2) * 2 + 1)
            item_y = (i // 2 + 1) * item_height  # 计算每个项的垂直位置
            item_positions.append(((CONFIG['screen']['width'] * item_width) // 4, item_y))

        return item_positions

    def draw(self):
        self.screen.blit(self.background, (0, 0))  # 绘制背景图片
        item_positions = self.calculate_item_positions()

        for i, character in self.characters.iterrows():
            character = character.to_dict()
            name_text = FONT.render(character['name'], True, BLACK)
            name_rect = name_text.get_rect(center=item_positions[i])
            self.rects[i] = name_rect

            # 计算蒙层的大小和位置
            overlay_rect = name_rect.inflate(20, 10)  # 给文字周围留出一些空间
            overlay = pygame.Surface((overlay_rect.width, overlay_rect.height), pygame.SRCALPHA)
            overlay.fill((255, 255, 255, 128))  # 白色半透明

            # 绘制蒙层到屏幕
            self.screen.blit(overlay, overlay_rect.topleft)

            # 绘制文字
            self.screen.blit(name_text, name_rect)

            # 绘制头像
            image_path = os.path.join(self.current_path, 'assets/head', f'{character["name"]}.png')
            avatar = pygame.image.load(image_path)
            avatar_rect = avatar.get_rect(center=(item_positions[i][0], item_positions[i][1] + 60))
            self.screen.blit(avatar, avatar_rect)